﻿using AutoMapper;
using B.S.BasicData.Api.Read.Application.Command.User;
using B.S.BasicData.Api.Read.DTO;
using B.S.BasicData.Domain;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;

namespace B.S.BasicData.Api.Read.Application.Handler.User
{
    public class GetUserHandler : IRequestHandler<GetUserCommand, ApiPaging<UserDTO>>
    {
        private readonly IBaseRepository<UserModel> userRepo;
        private readonly IBaseRepository<ShiModel> shiRepo;
        private readonly IBaseRepository<ShengModel> shengRepo;
        private readonly IBaseRepository<XianModel> xianRepo;
        private readonly IBaseRepository<UserRoleModel> userRoleRepo;
        private readonly IBaseRepository<RoleModel> roleRepo;

        public GetUserHandler(IBaseRepository<UserModel> userRepo, IBaseRepository<ShiModel> shiRepo, IBaseRepository<ShengModel> shengRepo, IBaseRepository<XianModel> xianRepo,IBaseRepository<UserRoleModel> userRoleRepo,IBaseRepository<RoleModel> roleRepo)
        {
            this.userRepo = userRepo;
            this.shiRepo = shiRepo;
            this.shengRepo = shengRepo;
            this.xianRepo = xianRepo;
            this.userRoleRepo = userRoleRepo;
            this.roleRepo = roleRepo;
        }


        public Task<ApiPaging<UserDTO>> Handle(GetUserCommand request, CancellationToken cancellationToken)
        {
            ApiPaging<UserDTO> res = new ApiPaging<UserDTO>();
            var user = userRepo.GetAll().Where(x => x.IsDelete == false);
            var userRole = userRoleRepo.GetAll();
            var role = roleRepo.GetAll();   
            var dto = (from a in user
                      join e in userRole on a.Id equals e.UserId into aeGroup
                      from e in aeGroup.DefaultIfEmpty()
                      join f in role on e.RoleId equals f.Id into efGroup
                      from f in efGroup.DefaultIfEmpty()
                      select new UserDTO
                      {
                          UpdateName = a.UpdateName,
                          CreateName = a.CreateName,
                          CreateTime = a.CreateTime,
                          UpdateTime = a.UpdateTime,
                          AddDesc = a.AddDesc,
                          Id = a.Id,
                          Sex = a.Sex,
                          Shnegid = a.Shnegid,
                          UserName = a.UserName,
                          ShiId = a.ShiId,
                          XianId = a.Xianid,
                          Bid = a.Bid,
                          RoleName = f.RoleName,
                      }).ToList();
            //排序进行数据显示
            var resultData= dto.OrderByDescending(x => x.Id).Skip((request.Index - 1) * request.Size).Take(request.Size).ToList();
            //创建一个字典，用于存储数据，建为int类型，值为UserDTO类型
            var mergeData = new Dictionary<int, UserDTO>();
            //循环排序的数据
            foreach (var item in resultData)
            {

                if (!mergeData.TryGetValue(item.Id,out var mergedItem))
                {
                    mergedItem = new UserDTO
                    {
                        Id = item.Id,
                        UserName = item.UserName,
                        Sex = item.Sex,
                        Shnegid = item.Shnegid,
                        CreateName = item.CreateName,
                        UpdateName = item.UpdateName,
                        RoleName = item.RoleName,
                        AddDesc = item.AddDesc,
                        Bid = item.Bid,
                        CreateTime = item.CreateTime,
                        ShiId = item.ShiId,
                        UpdateTime = item.UpdateTime,
                        XianId = item.XianId,
                    };
                    mergeData[item.Id]= mergedItem;
                }
                else
                {
                    mergedItem.RoleName += "、" + item.RoleName;
                }
            }
            res.TotalCount = dto.Count();
            res.TotalPage = (int)Math.Ceiling(res.TotalCount * 1.0 / request.Size);
            res.Datas = mergeData.Values.ToList();
            res.Msg = "分页显示用户信息";
            res.Code = ApiEnum.Success;
            return Task.FromResult(res);
        }
    }
}
